<template>
    <div class="factory-wrapper">
        <IHeader class="header" back="true" title="找工厂" publish="true"></IHeader>
        <scroller class="material-content">
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="标题" :erro="materialForm.title.error"></Label>
                <input v-model="materialForm.title.value" class="write enterpriseName" placeholder="请输入" type="text">
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb" @click="handleSelectType">
                <Label content="产品类型" :error="materialForm.productType.error"></Label>
                <div class="handleChoose flex_row">
                    <text class="fs_28" :class="[materialForm.productType.value === '请选择' ? 'col_cecece' : 'col_464646']">{{materialForm.productType.value}}</text>
                    <image class="arrow_right_small" :src="imgPath('arrow_right_small.png')"></image>
                </div>
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="出口国家" :error="materialForm.output.error"></Label>
                <input v-model="materialForm.output.value" class="write enterpriseName" placeholder="请输入" type="text">
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="配色" :error="materialForm.color.error"></Label>
                <input v-model="materialForm.color.value" class="write enterpriseName" placeholder="请输入" type="text">
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="码段" :error="materialForm.codeSegment.error"></Label>
                <input v-model="materialForm.codeSegment.value" class="write enterpriseName" placeholder="请输入" type="text">
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="订单数量" :error="materialForm.number.error"></Label>
                <input v-model="materialForm.number.value" class="write enterpriseName" placeholder="请输入" type="number">
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb" @click="handleSelectDate('deliveryDate')">
                <Label content="交货日期" :error="materialForm.deliveryDate.error"></Label>
                <div class="handleChoose flex_row">
                    <text class="fs_28" :class="[materialForm.deliveryDate.value === '请选择' ? 'col_cecece' : 'col_464646']">{{materialForm.deliveryDate.value}}</text>
                    <image class="arrow_right_small" :src="imgPath('arrow_right_small.png')"></image>
                </div>
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="联系人" :error="materialForm.contact.error"></Label>
                <input v-model="materialForm.contact.value" class="write enterpriseName" placeholder="请输入" type="text">
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb">
                <Label content="联系人电话" :error="materialForm.contactPhone.error"></Label>
                <input v-model="materialForm.contactPhone.value" @blur="checkPhone" class="write enterpriseName" placeholder="请输入" type="tel">
            </div>
            <div class="info-cell border-bottom-ebebeb introduce-wrapper">
                <Label content="其它要求" :error="materialForm.introduction.error"></Label>
                <textarea class="enterpriseIntroduce" v-model="materialForm.introduction.value" placeholder="请输入工艺、技术等" maxlength="500"></textarea>
                <text class="word-number">{{countWord + '/500'}}</text>
            </div>
            <div class="info-cell flex_row border-bottom-ebebeb no-single">
                <Label content="图片上传"></Label>
                <div class="image-container flex_row">
                    <div class="image-content flex_row" v-if="materialForm.imageList.value.length > 0">
                        <div class="image-box" :class="[(index !== 0) ? 'margin_left_12' : '']" v-for="(item, index) in materialForm.imageList.value" :key="index">
                            <image class="scene-image" :src="item"></image>
                            <image class="delete-image" :src="imgPath('image_delete.png')" @click="handleDeleteImage(index)"></image>
                        </div>
                    </div>
                    <Uploader @doclick="handleUploadImage" v-if="materialForm.imageList.value.length < 3"></Uploader>
                </div>
            </div>
            <div class="info-cell flex_row item-height border-bottom-ebebeb" @click="handleSelectDate('taskDate')">
                <Label content="任务有效期"></Label>
                <div class="handleChoose flex_row">
                    <text class="fs_28" :class="[materialForm.taskDate.value === '请选择' ? 'col_cecece' : 'col_464646']">{{materialForm.taskDate.value}}</text>
                    <image class="arrow_right_small" :src="imgPath('arrow_right_small.png')"></image>
                </div>
            </div>
            <Buttons class="nextStep" word="发布" @doclick="handleNextStep"></Buttons>
        </scroller>
        <!--产品类型弹窗-->
        <wxc-popup popup-color="#fff" :show="typeSelectShow" @wxcPopupOverlayClicked="closeTypeDialog" pos="right">
            <div class="dialog-content">
                <IHeader class="header" back="true" close="true" title="选择产品类型" @closeDialog="closeTypeDialog"></IHeader>
                <list class="enterprise-list">
                    <cell class="enterprise-item" @click="chooseThisMaterial(item, index)" v-for="(item, index) in productType" :key="index">
                        <text class="fs_28 item-height col_464646" :class="[(index === productType.length - 1) ? '' : 'border-bottom-cecece']">{{item}}</text>
                    </cell>
                </list>
            </div>
        </wxc-popup>
        <!--loading-->
        <wxc-loading :show="loadingShow" :need-mask="needMask"></wxc-loading>
    </div>
</template>

<script>
import IHeader from '@/components/header'
import Label from '@/components/label'
import Question from '@/components/question'
import Uploader from '@/components/imageUpload'
import Buttons from '@/components/buttons'
import { WxcPopup, WxcLoading } from 'weex-ui'
import { validatenull, validatePhone, isvalidatemobile } from '@/util/validate'
import { submitFactory, editFactory, getLookingDetail } from '@/api/market'
import { fileUpload } from '@/api/common'
import Nat from 'natjs'

const modal = weex.requireModule('modal')
const picker = weex.requireModule('picker')

export default {
  name: 'factory',
  data () {
    return {
      id: '', // 任务id
      extId: '', // 发布id
      loadingShow: false, // loading
      needMask: true,
      imageIndex: 0, // 上传下标
      typeSelectShow: false, // 选择布料类型弹窗显示
      productType: ['比基尼', '分体泳衣', '连体泳衣', '男士泳裤', '大码泳装', '儿童泳装', '其他'], // 产品类型
      materialForm: { // 工厂表单
        title: {
          value: '',
          name: '标题',
          error: false
        }, // 标题
        productType: {
          value: '请选择',
          name: '产品类型',
          error: false
        }, // 产品类型
        output: {
          value: '',
          name: '出口国家',
          error: false
        }, // 出口国家
        color: {
          value: '',
          name: '配色',
          error: false
        }, // 配色
        codeSegment: {
          value: '',
          name: '码段',
          error: false
        }, // 码段
        number: {
          value: '',
          name: '订单数量',
          error: false
        }, // 订单数量
        deliveryDate: {
          value: '请选择',
          name: '交货日期',
          error: false
        }, // 交货日期
        contact: {
          value: '',
          name: '联系人',
          error: false
        }, // 联系人
        contactPhone: {
          value: '',
          name: '联系人电话',
          error: false
        }, // 联系人电话
        introduction: {
          value: '',
          name: '其他要求',
          error: false
        }, // 说明
        imageList: {
          value: [],
          name: '图片',
          error: false
        }, // 图片
        taskDate: {
          value: '请选择',
          name: '任务有效期',
          error: false
        } // 任务有效期
      }
    }
  },
  computed: {
    countWord () {
      return this.materialForm.introduction.value.length
    }
  },
  created () {
    const that = this
    that.id = that.$route.query.id
    that.extId = that.$route.query.extId
    if (validatenull(that.id)) {
      return
    }
    that.loadingShow = true
    that.$api.get(getLookingDetail + that.id, {}, (res) => {
      let dataObj = res.data
      that.materialForm.title.value = dataObj.yykFactory.title
      that.materialForm.productType.value = dataObj.yykFactory.produceType
      that.materialForm.output.value = dataObj.yykFactory.exportingCountries
      that.materialForm.color.value = dataObj.yykFactory.color
      that.materialForm.codeSegment.value = dataObj.yykFactory.codeSegment
      that.materialForm.number.value = dataObj.yykFactory.orderNumber
      that.materialForm.deliveryDate.value = dataObj.yykFactory.deliveryDate
      that.materialForm.contact.value = dataObj.yykFactory.contact
      that.materialForm.contactPhone.value = dataObj.yykFactory.contactPhone
      that.materialForm.introduction.value = dataObj.yykFactory.otherRequirements
      that.materialForm.taskDate.value = dataObj.yykFactory.taskValidity
      let images = dataObj.yykFactory.imagesUrl.split(',')
      images.forEach((item) => {
        that.materialForm.imageList.value.push(item)
      })
      that.loadingShow = false
    })
  },
  methods: {
    handleSelectType () { // 选择产品类型
      this.typeSelectShow = true
    },
    closeTypeDialog () { // 关闭产品布料类型
      this.typeSelectShow = false
    },
    chooseThisMaterial (name, inx) { // 产品类型选择
      this.materialForm.productType.value = name
      // this.materialForm.productType.type = inx + 1
      this.typeSelectShow = false
    },
    checkPhone () { // 验证联系人电话
      const that = this
      if (!validatePhone(that.materialForm.contactPhone.value).result && !isvalidatemobile(that.materialForm.contactPhone.value).result) {
        that.modalShow = true
        that.modalWord = that.materialForm.contactPhone.name + '信息有误'
        that.materialForm.contactPhone.error = true
        setTimeout(() => {
          that.modalShow = false
        }, 2000)
        return
      }
      that.materialForm.contactPhone.error = false
    },
    handleSelectDate (type) { // 选择时间
      const that = this
      let date = '' // 日期
      let time = '' // 时间
      picker.pickDate({
        value: date
      }, e => {
        if (e.result === 'success') {
          date = e.data
          setTimeout(() => {
            picker.pickTime({
              value: time
            }, event => {
              if (event.result === 'success') {
                time = event.data
                for (let i in that.materialForm) {
                  if (type === i) {
                    that.materialForm[i].value = date + ' ' + time + ':00'
                  }
                }
              }
            })
          }, 100)
        }
      })
    },
    uploadImage (list) { // 上传动作
      const that = this
      if (that.imageIndex >= list.length) {
        return
      }
      that.loadingShow = true
      Nat.upload(that.$api.url + fileUpload, {
        path: list[that.imageIndex]
      }, (errs, res) => {
        if (errs) {
          modal.toast({
            message: '[ERROR] ' + JSON.stringify(errs)
          })
          return
        }
        if (res.ok) {
          let data = JSON.parse(res.data)
          let imageUrl = data.data
          that.materialForm.imageList.value.push(imageUrl)
          that.loadingShow = false
          that.imageIndex++
          that.uploadImage(list)
        }
      })
    },
    handleUploadImage () { // 图片上传
      const that = this
      Nat.image.pick({
        limit: 3,
        showCamera: true
      }, (err, ret) => {
        if (err) {
          modal.toast({
            message: '[ERROR] ' + JSON.stringify(err)
          })
          return
        }
        that.loadingShow = true
        let paths = ret.paths
        that.imageIndex = 0
        that.uploadImage(paths)
      })
    },
    handleDeleteImage (inx) { // 删除图片
      const that = this
      that.materialForm.imageList.value.splice(inx, 1)
    },
    handleNextStep () { // 发布
      const that = this
      for (let i in that.materialForm) {
        if (!validatenull(that.materialForm[i].name)) {
          if (that.materialForm[i].error || validatenull(that.materialForm[i].value) || that.materialForm[i].value === '请选择' || that.materialForm[i].value <= 0 || that.materialForm[i].type < 0) {
            that.modalShow = true
            that.modalWord = that.materialForm[i].name + '信息有误'
            that.materialForm[i].error = true
            setTimeout(() => {
              that.modalShow = false
              that.materialForm[i].error = false
            }, 2000)
            return
          }
        }
      }
      let nowTime = that.getNowDate()
      if (that.materialForm.deliveryDate.value < nowTime || that.materialForm.taskDate.value < nowTime) {
        modal.toast({
          message: '选择时间不能比当前时间早'
        })
        return
      }
      if (that.materialForm.deliveryDate.value < that.materialForm.taskDate.value) {
        modal.toast({
          message: '交货日期不能比任务有效期早'
        })
        return
      }
      let params = {
        title: that.materialForm.title.value,
        produceType: that.materialForm.productType.value,
        exportingCountries: that.materialForm.output.value,
        color: that.materialForm.color.value,
        codeSegment: that.materialForm.codeSegment.value,
        orderNumber: that.materialForm.number.value,
        deliveryDate: that.materialForm.deliveryDate.value,
        contact: that.materialForm.contact.value,
        contactPhone: that.materialForm.contactPhone.value,
        otherRequirements: that.materialForm.introduction.value,
        imagesUrl: that.materialForm.imageList.value.join(','),
        taskValidity: that.materialForm.taskDate.value
      }
      let url = validatenull(that.id) ? submitFactory : editFactory
      if (!validatenull(that.id)) {
        params.id = that.extId
      }
      that.loadingShow = true
      that.$api.post(url, params, () => {
        that.loadingShow = false
        modal.toast({
          message: '发布成功'
        })
        setTimeout(() => {
          that.$router.push('/mine/myPublic')
        }, 500)
      }, () => {
        that.loadingShow = false
      }, true)
    }
  },
  components: {
    IHeader,
    Label,
    Buttons,
    WxcPopup,
    WxcLoading,
    Question,
    Uploader
  }
}
</script>

<style scoped>
    .col_cecece {
        color: #cecece;
    }
    .col_464646 {
        color: #464646;
    }
    .flex_row {
        flex-direction: row;
    }
    .fs_28 {
        font-size: 28px;
    }
    .border-bottom-cecece {
        border-bottom-width: 1px;
        border-bottom-style: solid;
        border-bottom-color: #cecece;
    }
    .border-bottom-ebebeb {
        border-bottom-width: 1px;
        border-bottom-style: solid;
        border-bottom-color: #ebebeb;
    }
    .item-height {
        height: 88px;
        line-height: 88px;
    }
    .material-content {
        padding-top: 100px;
        /*background-color: #f5f5f5;*/
    }
    .info-cell {
        padding-left: 24px;
        padding-right: 24px;
        justify-content: space-between;
    }
    .content-tit {
        padding-left: 24px;
        padding-right: 24px;
        color: #a4a4a4;
        font-size: 28px;
        background-color: #fff;
    }
    .handleChoose {
        align-items: center;
    }
    .arrow_right_small {
        width: 27px;
        height: 28px;
        margin-left: 16px;
    }
    .enterprise-item {
        padding-left: 24px;
        padding-right: 24px;
    }
    .write {
        padding-right: 44px;
        text-align: right;
        border-width: 0px;
        font-size: 28px;
        color: #464646;
        placeholder-color: #cecece;
    }
    .enterpriseName {
        width: 480px;
        lines: 1;
    }
    .enterpriseIntroduce {
        width: 654px;
        height: 200px;
        margin-top: 16px;
        margin-left: 24px;
        padding-top: 16px;
        padding-right: 16px;
        padding-bottom: 16px;
        padding-left: 16px;
        border-width: 1px;
        border-style: solid;
        border-color: #ebebeb;
        font-size: 28px;
        color: #464646;
        placeholder-color: #cecece;
    }
    .introduce-wrapper {
        padding-top: 20px;
        border-bottom-width: 0px;
    }
    .word-number {
        flex: 1;
        padding-right: 24px;
        font-size: 24px;
        line-height: 64px;
        color: #cecece;
        text-align: right;
    }
    .no-single {
        padding-top: 20px;
        padding-bottom: 24px;
        flex-wrap: wrap;
        justify-content: flex-start;
    }
    .image-container {
        width: 702px;
        margin-top: 20px;
    }
    .margin_left_12 {
        margin-left: 12px;
    }
    .image-content {
        margin-right: 12px;
    }
    .scene-image {
        width: 226px;
        height: 226px;
    }
    .delete-image {
        position: absolute;
        top: 4px;
        right: 4px;
        width: 36px;
        height: 36px;
    }
    .nextStep {
        margin-top: 98px;
        margin-bottom: 144px;
    }
    .enterprise-list {
        min-height: 700px;
        margin-top: 88px;
    }
</style>
